import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Bell, Check, X, Heart, MessageCircle } from 'lucide-react';
import { useAuthStore, useNotificationStore } from '../stores';
import { apiService } from '../services/api';
import toast from 'react-hot-toast';
import { formatDistanceToNow } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import type { Notification } from '../types/api';

const NotificationsPage: React.FC = () => {
  const { user } = useAuthStore();
  const { notifications, setNotifications, markAsRead, setUnreadCount } = useNotificationStore();
  const [isLoading, setIsLoading] = useState(true);

  // 获取通知列表
  useEffect(() => {
    const fetchNotifications = async () => {
      if (!user) return;

      try {
        const response = await apiService.getNotifications(user.user_id, 1, 50);
        if (response.code === 0) {
          setNotifications(response.data.notifications);
          setUnreadCount(response.data.notifications.filter(n => !n.is_read).length);
        }
      } catch (error) {
        console.error('Fetch notifications error:', error);
        toast.error('获取通知列表失败');
      } finally {
        setIsLoading(false);
      }
    };

    fetchNotifications();
  }, [user, setNotifications, setUnreadCount]);

  const handleMarkAsRead = async (notificationId: number) => {
    if (!user) return;

    try {
      await apiService.markNotificationAsRead(user.user_id, notificationId);
      markAsRead(notificationId);
      toast.success('已标记为已读');
    } catch (error) {
      console.error('Mark notification read error:', error);
    }
  };

  const formatNotificationTime = (timeString: string) => {
    try {
      return formatDistanceToNow(new Date(timeString), { 
        addSuffix: true, 
        locale: zhCN 
      });
    } catch {
      return '刚刚';
    }
  };

  const getNotificationIcon = (type: number) => {
    switch (type) {
      case 1: // 匹配通知
        return <Heart className="text-red-500" size={20} />;
      case 2: // 消息通知
        return <MessageCircle className="text-blue-500" size={20} />;
      default:
        return <Bell className="text-gray-500" size={20} />;
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">加载通知中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 pt-20">
      <div className="max-w-md mx-auto px-4">
        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-6"
        >
          <h1 className="text-2xl font-bold text-gray-900">通知</h1>
          <p className="text-gray-600">你收到 {notifications.length} 条通知</p>
        </motion.div>

        {/* 通知列表 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.2 }}
          className="space-y-4"
        >
          {notifications.length === 0 ? (
            <div className="text-center py-12">
              <div className="w-20 h-20 bg-gray-200 rounded-full mx-auto mb-4 flex items-center justify-center">
                <Bell className="text-gray-400" size={32} />
              </div>
              <h2 className="text-xl font-semibold text-gray-900 mb-2">暂无通知</h2>
              <p className="text-gray-600">当你收到新消息或匹配时，会在这里显示</p>
            </div>
          ) : (
            notifications.map((notification, index) => (
              <motion.div
                key={notification.notification_id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.1 }}
                className={`bg-white rounded-xl p-4 shadow-sm hover:shadow-md transition-shadow duration-200 ${
                  !notification.is_read ? 'border-l-4 border-primary-500' : ''
                }`}
              >
                <div className="flex items-start space-x-3">
                  {/* 通知图标 */}
                  <div className="flex-shrink-0 mt-1">
                    {getNotificationIcon(notification.type)}
                  </div>

                  {/* 通知内容 */}
                  <div className="flex-1 min-w-0">
                    <div className="flex items-start justify-between mb-2">
                      <h3 className="text-sm font-semibold text-gray-900">
                        {notification.title}
                      </h3>
                      {!notification.is_read && (
                        <span className="w-2 h-2 bg-primary-500 rounded-full flex-shrink-0 mt-2"></span>
                      )}
                    </div>
                    
                    <p className="text-sm text-gray-600 mb-2">
                      {notification.content}
                    </p>
                    
                    <div className="flex items-center justify-between">
                      <span className="text-xs text-gray-500">
                        {formatNotificationTime(notification.created_at)}
                      </span>
                      
                      {!notification.is_read && (
                        <button
                          onClick={() => handleMarkAsRead(notification.notification_id)}
                          className="text-xs text-primary-500 hover:text-primary-600 font-medium"
                        >
                          标记已读
                        </button>
                      )}
                    </div>
                  </div>
                </div>
              </motion.div>
            ))
          )}
        </motion.div>

        {/* 底部操作 */}
        {notifications.length > 0 && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.5 }}
            className="mt-8 pb-8"
          >
            <div className="flex space-x-3">
              <button className="flex-1 btn-outline py-3">
                全部标记已读
              </button>
              <button className="flex-1 btn-secondary py-3">
                清空通知
              </button>
            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
};

export default NotificationsPage;
